// 修正导入部分，移除不存在的FormItem
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import {
  TextArea,
  Button,
  Modal,
  Col,
  Row,
} from '@douyinfe/semi-ui';
import { Image, Select as ArcoSelect, Form, Message } from '@arco-design/web-react';
import deleteIcon from '@/assets/images/imageEdit/delete.svg';
import styles from './videoConfig.module.scss';
import UploadComponent from '../components/UploadComponent';
import { useDispatch } from 'react-redux';
import { useBlobUrlManager } from '@/pages/imageEdit/components/MainEdit/hooks/useBlobUrlManager.js';
import HistoryModal from '../components/HistoryModal';
import UploadPreviewModal from '../components/UploadPreviewModal';
import { uploadImage } from '@/api/common';
import VideoSelectConfig from '../../common/videoSelectConfig';
import { imgToVideo, getHistoryFilesByImgAllPage } from '@/api/video';
import { useLoading } from '@/components/common/mlsLoading/laodingText';

const FormItem = Form.Item;

const MENU_HEIGHTS = {
  pic: { area: '353px', textArea: '360px' },
  multi: { area: '134px', textArea: '224px' },
  imageToVideo: { area: '134px', textArea: '224px' },
  image: { area: '227px' },
  default: { area: '', textArea: '' },
};

export default function MainEdit({ currentMenuKey, currentMenuTitle }) {
  // 获取高度配置
  const heights = MENU_HEIGHTS[currentMenuKey] || MENU_HEIGHTS.default;

  // 添加分镜配置弹窗状态
  const [storyboardModalVisible, setStoryboardModalVisible] = useState(false);

  // 分镜表单数据状态
  const [storyboardForm, setStoryboardForm] = useState({
    script: '', // 剧本
    storyUnit: '', // 故事单元
    scene: '', // 场景
    shotNumber: '', // 镜号
    prompt: '', // 分镜视频提示词
  });

  // 模拟数据选项
  const scriptOptions = [
    { label: '剧本1', value: 'script1' },
    { label: '剧本2', value: 'script2' },
    { label: '剧本3', value: 'script3' },
  ];

  const storyUnitOptions = [
    { label: '单元1', value: 'unit1' },
    { label: '单元2', value: 'unit2' },
    { label: '单元3', value: 'unit3' },
  ];

  const sceneOptions = [
    { label: '场景1', value: 'scene1' },
    { label: '场景2', value: 'scene2' },
    { label: '场景3', value: 'scene3' },
  ];

  const shotNumberOptions = [
    { label: '1镜', value: 'shot1' },
    { label: '2镜', value: 'shot2' },
    { label: '3镜', value: 'shot3' },
    { label: '4镜', value: 'shot4' },
    { label: '5镜', value: 'shot5' },
  ];

  const [historyModal, setHistoryModal] = useState(false);
  const [referImagesList, setReferImagesList] = useState(new Set());
  // 视频提示词
  const [promptText, setPromptText] = useState(undefined);
  const [ratio, setRatio] = useState('16:9');
  const [resolution, setResolution] = useState('1080p');
  const [duration, setDuration] = useState('short');
  const [deviceApi, setDeviceApi] = useState(undefined);
  const [deviceApiLabel, setDeviceApiLabel] = useState(undefined);
  const { showLoading, hideLoading } = useLoading();

  const [imageHistoryList, setImageHistoryList] = useState([]);

  const [uploadingKey, setUploadingKey] = useState('');

  // 上传图片后预览弹窗
  const [previewSelectedKey, setPreviewSelectedKey] = useState('');
  const [previewModalVisible, setPreviewModalVisible] = useState(false);

  const handlePreviewConfirm = useCallback(({imageList, selectedKey, selectedType }) => {
    // 处理确认逻辑，可以使用选中的区域类型
    setReferImagesList(prev => {
      console.log('handlePreviewConfirm 更新后的数据:', imageList);
      const newList = Array.from(prev).map(item => {
        if(item.key !== selectedKey) {
          return item;
        }
        return {...item, referType: selectedType};
      })
      return new Set(newList);
    });

    setPreviewModalVisible(false);
    setPreviewSelectedKey('');
  }, []);

  // 使用自定义Hook管理blob URLs
  const { createBlobUrl, cleanupUnusedUrls } = useBlobUrlManager();

  // 打开分镜配置弹窗
  const openStoryboardModal = () => {
    console.log('currentMenuKey', 1);
    setStoryboardModalVisible(true);
  };

  // 关闭分镜配置弹窗
  const closeStoryboardModal = () => {
    setStoryboardModalVisible(false);
  };

  // 处理表单字段变化
  const handleFormChange = (field, value) => {
    // console.log('field', field, 'value', value);

    setStoryboardForm(prev => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleHistoryClick = useCallback((e, key) => {
    e.stopPropagation(); // 阻止事件冒泡，防止触发Upload的点击事件
    console.log('handleHistoryClick', key);
    setUploadingKey(key);
    setHistoryModal(true);
  }, []);

  const handleHistoryModalCancel = useCallback(() => {
    setHistoryModal(false);
    setUploadingKey('');
  }, []);

  const handleHistoryModalConfirm = useCallback((key, obj) => {
    console.log('handleHistoryModalConfirm', key, obj);
    setReferImagesList(prev => {
      const prevArray = Array.from(prev);
      // 使用更清晰的逻辑处理更新和新增
      const itemExists = prevArray.some(item => item.key === key);
      const newList = itemExists
        ? prevArray.map(item => (item.key === key ? { ...item, ...obj } : item))
        : [...prevArray, { ...obj, key }];
      return new Set(newList);
    });
    setHistoryModal(false);
    setUploadingKey('');
  }, []);

  // 确认使用分镜配置
  const confirmStoryboardConfig = () => {
    // 这里可以添加处理分镜配置的逻辑
    console.log('使用分镜配置:', storyboardForm);

    // 关闭弹窗
    closeStoryboardModal();
  };

  const handleUpload = useCallback(
    ({ file, uploadKey }) => {
      console.log(uploadKey, file);
      // 自己调用文件上传接口
      uploadImage(file, file.name).then(res => {
        let imageKey = `${currentMenuKey}_${uploadKey}`; 
        console.log('handleUpload1', Array.from(referImagesList));
        let arr = Array.from(referImagesList).filter(item => item.key !== imageKey);
        const obj = {
          key: imageKey,
          imageUrl: res.url,
          referType: 'subject',
        };
        const newSet = new Set(arr);
        newSet.add(obj);
        console.log('handleUpload2', Array.from(newSet));

        
        setReferImagesList(newSet);
        // 上传成功后，设置预览弹窗可见,且默认预览对应的图片
        setPreviewModalVisible(true);
        // 同时设置默认预览图片的key
        setPreviewSelectedKey(`${currentMenuKey}_${uploadKey}`);
        
      });
    },
    [uploadImage, setPreviewModalVisible, setReferImagesList, currentMenuKey, referImagesList]
  );

  const onDeleteImage = useCallback(
    (imageKey) => {
      console.log('onDeleteImage', imageKey);
      
      let arr = Array.from(referImagesList).filter(item => item.key !== imageKey);
      console.log('onDeleteImage', arr);
      setReferImagesList(new Set(arr));
    },
    [referImagesList, setReferImagesList]
  );

  const renderMenuContent = useCallback(() => {
    return (
      <>
        <div className={styles.titleSection}>参考图</div>
        <div className={`${styles.area}`} style={{ maxHeight: heights.area, flexDirection: 'row' }}>
          {
            <>
              <UploadComponent
                title="上传图片"
                uploadKey="AT"
                subtitle=""
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={e => handleHistoryClick(e, `${currentMenuKey}_AT`)}
                referImagesList={referImagesList}
                onDeleteImage={onDeleteImage}
                imageContent={Array.from(referImagesList).find(
                  item => item.key === `${currentMenuKey}_AT`
                )}
              />
              <UploadComponent
                title="上传图片"
                uploadKey="BT"
                subtitle=""
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={e => handleHistoryClick(e, `${currentMenuKey}_BT`)}
                referImagesList={referImagesList}
                onDeleteImage={onDeleteImage}
                imageContent={Array.from(referImagesList).find(
                  item => item.key === `${currentMenuKey}_BT`
                )}
              />
              <UploadComponent
                title="上传图片"
                uploadKey="CT"
                subtitle=""
                currentMenuKey={currentMenuKey}
                onUpload={handleUpload}
                onHistoryClick={e => handleHistoryClick(e, `${currentMenuKey}_CT`)}
                referImagesList={referImagesList}
                onDeleteImage={onDeleteImage}
                imageContent={Array.from(referImagesList).find(
                  item => item.key === `${currentMenuKey}_CT`
                )}
              />
            </>
          }
        </div>
      </>
    );
  }, [currentMenuKey, heights.area, handleUpload, handleHistoryClick, referImagesList]);

  // 渲染参考提示词区域
  const renderReferencePromptSection = useCallback(
    (placeholder = '请在此输入提示词，描述视频内容...') => (
      <>
        <div className={styles.titleSection}>参考提示词</div>
        <div className={styles.area} style={{ maxHeight: 496 }}>
          <TextArea value={promptText} placeholder={placeholder} onChange={setPromptText} />

          <div className={styles.opts}>
            <Image
              className={styles.img}
              src={deleteIcon}
              preview={false}
              draggable={false}
              onClick={() => setPromptText('')}
            />
            {/* <div className={styles.opt} onClick={openStoryboardModal} style={{ cursor: 'pointer' }}>
            <Image src={text_mirror} preview={false} draggable={false} />
            <div className={styles.text}>使用分镜脚本</div>
          </div> */}
          </div>
        </div>
      </>
    ),
    [heights.textArea, promptText, setPromptText]
  );

  const savePrit = e => {
    console.log(e);
  };

  const onDeviceApiChange = useCallback(
    ({ value, label }) => {
      console.log('onDeviceApiChange', value, label);

      setDeviceApi(value);
      setDeviceApiLabel(label);
    },
    [setDeviceApi, setDeviceApiLabel]
  );

  const generateVideo = useCallback(() => {
    console.log('generateVideo', promptText);
    // 判断是否上传了参考图
    if(!referImagesList.size) {
      Message.error('请上传参考图');
      return;
    }
    if (!promptText) {
      Message.error('请输入提示词');
      return;
    }
    if (!deviceApi) {
      Message.error('请选择API');
      return;
    }

    let obj = {
      text: promptText,
      ratio,
      resolution,
      api: deviceApi,
      apiName: deviceApiLabel,
      duration,
      referImages: Array.from(referImagesList).map(item => {
        return {
          imageUrl: item.imageUrl,
          referType: item.referType,
        };
      }),
    };
    showLoading('生成中...');
    imgToVideo(obj)
      .then(res => {
        console.log('textToVideo', res);
      })
      .catch(err => {
        console.log('textToVideo err', err);
        hideLoading();
      });
  }, [promptText, ratio, resolution, deviceApi, duration, referImagesList]);

  useEffect(() => {
    // 初始化获取图生视频历史文件列表
    getHistoryFilesByImgAllPage({
      pageNum: 1,
      pageSize: 100,
    }).then(res => {
      if (res.code === 200) {
        setImageHistoryList(res.data?.urls || []);
      }
    });
  }, []);

  return (
    <div className={styles.mainEdit}>
      <div className={styles.top}>
        <div className={styles.header}>
          <div className={styles.title}>{currentMenuTitle}</div>
        </div>
        {renderMenuContent()}
        {renderReferencePromptSection()}

        {/* <Checkbox
            className={styles.saveBtn}
            onChange={ savePrit }
            aria-label="保存脚本修改"
        >
            保存脚本修改
        </Checkbox> */}
      </div>
      {
        <div className={styles.bottom}>
          <VideoSelectConfig
            duration={duration}
            onDurationChange={setDuration}
            resolution={resolution}
            onResolutionChange={setResolution}
            ratio={ratio}
            onRatioChange={setRatio}
            deviceApi={deviceApi}
            onDeviceApiChange={onDeviceApiChange}
            onGenerate={generateVideo}
            scene="reference2video"
          />
        </div>
      }

      {/* 分镜配置弹窗 - 使用Arco组件改造 */}
      <Modal
        title="分镜脚本"
        visible={storyboardModalVisible}
        footer={
          <div className={styles.historyModalButton}>
            {/* <Button 
              onClick={closeStoryboardModal} 
              className={`${styles.button} button buttonDefault`}
            >
              取消
            </Button> */}
            <Button
              onClick={confirmStoryboardConfig}
              className={`${styles.button} button buttonPrimary`}
              style={{ width: '100%', borderRadius: '8px' }}>
              确认
            </Button>
          </div>
        }
        width={600}
        centered>
        <div className={styles.storyboardModalContent}>
          <Form
            layout="horizontal"
            labelAlign="left"
            labelWidth={100}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            className={styles.formLayout}>
            <Row gutter={16}>
              {/* First row: Script and Story Unit */}
              <Col span={12}>
                <FormItem label="剧本:" field="script">
                  <ArcoSelect
                    value={storyboardForm.script}
                    onChange={value => handleFormChange('script', value)}
                    placeholder="请选择剧本"
                    style={{ width: '100%' }}>
                    {scriptOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="故事单元:" field="storyUnit">
                  <ArcoSelect
                    value={storyboardForm.storyUnit}
                    onChange={value => handleFormChange('storyUnit', value)}
                    placeholder="请选择故事单元"
                    style={{ width: '100%' }}>
                    {storyUnitOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginTop: '16px' }}>
              {/* Second row: Scene and Shot Number */}
              <Col span={12}>
                <FormItem label="场景:" field="scene">
                  <ArcoSelect
                    value={storyboardForm.scene}
                    onChange={value => handleFormChange('scene', value)}
                    placeholder="请选择场景"
                    style={{ width: '100%' }}>
                    {sceneOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="镜号:" field="shotNumber">
                  <ArcoSelect
                    value={storyboardForm.shotNumber}
                    onChange={value => handleFormChange('shotNumber', value)}
                    placeholder="请选择镜号"
                    style={{ width: '100%' }}>
                    {shotNumberOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
            </Row>

            {/* Third row: Storyboard Video Prompt */}
            <Row style={{ marginTop: '16px' }}>
              <Col span={24}>
                <FormItem label="分镜视频提示词" field="prompt" layout="vertical">
                  <TextArea
                    placeholder="请输入分镜视频提示词..."
                    value={storyboardForm.prompt}
                    onChange={e => handleFormChange('prompt', e)}
                    autosize={{ minRows: 4, maxRows: 6 }}
                    className={styles.textArea}
                  />
                </FormItem>
              </Col>
            </Row>

            <Row style={{ marginTop: '12px' }}>
              <Col span={24}>
                <span style={{ fontSize: '14px', color: '#fff', opacity: 0.8 }}>
                  建议API：可灵２.１大师版
                </span>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>

      <HistoryModal
        visible={historyModal}
        onCancel={handleHistoryModalCancel}
        onConfirm={handleHistoryModalConfirm}
        isShowArea={true}
        imageHistoryList={imageHistoryList}
        uploadingKey={uploadingKey}
      ></HistoryModal>

      <UploadPreviewModal
        visible={previewModalVisible}
        onCancel={() => setPreviewModalVisible(false)}
        onConfirm={handlePreviewConfirm}
        imageList={Array.from(referImagesList)}
        selectedKey={previewSelectedKey}
      />
    </div>
  );
}
